package com.agrimall.servlet.merchant;

import com.agrimall.entity.Order;
import com.agrimall.entity.User;
import com.agrimall.service.OrderService;
import com.agrimall.service.impl.OrderServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商家售后管理Servlet
 */
@WebServlet("/merchant/afterSale")
public class AfterSaleManageServlet extends HttpServlet {
    private OrderService orderService = new OrderServiceImpl();
    private ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User merchant = (User) session.getAttribute("merchant");
        
        if (merchant == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        String action = request.getParameter("action");
        
        if (action == null || action.equals("") || action.equals("list")) {
            // 售后订单列表
            listAfterSaleOrders(request, response, merchant);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User merchant = (User) session.getAttribute("merchant");
        
        if (merchant == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        String action = request.getParameter("action");
        
        if (action != null && action.equals("complete")) {
            // 完成售后订单
            completeAfterSaleOrder(request, response, merchant);
        } else if (action != null && action.equals("batchDelete")) {
            // 批量删除订单
            batchDeleteOrders(request, response, merchant);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    /**
     * 售后订单列表（只显示状态为5-售后中的订单）
     */
    private void listAfterSaleOrders(HttpServletRequest request, HttpServletResponse response, User merchant)
            throws ServletException, IOException {
        String pageStr = request.getParameter("page");
        String orderNo = request.getParameter("orderNo");
        
        int page = 1;
        if (pageStr != null && !pageStr.isEmpty()) {
            try {
                page = Integer.parseInt(pageStr);
            } catch (NumberFormatException e) {
                page = 1;
            }
        }
        int pageSize = 10;
        
        // 查询状态为5（售后中）的订单
        List<Order> orders = orderService.getOrderListByMerchantAndStatus(merchant.getUserId(), 5, page, pageSize);
        int totalCount = orderService.countOrdersByMerchantAndStatus(merchant.getUserId(), 5);
        
        // 计算总页数
        int totalPages = totalCount > 0 ? (int) Math.ceil((double) totalCount / pageSize) : 1;
        
        request.setAttribute("orders", orders);
        request.setAttribute("page", page);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("orderNo", orderNo);
        
        request.getRequestDispatcher("/merchant/afterSale/list.jsp").forward(request, response);
    }
    
    /**
     * 完成售后订单（将状态从5-售后中改为3-已完成）
     */
    private void completeAfterSaleOrder(HttpServletRequest request, HttpServletResponse response, User merchant)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String orderIdStr = request.getParameter("orderId");
            if (orderIdStr == null || orderIdStr.trim().isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "订单ID不能为空");
                out.print(objectMapper.writeValueAsString(result));
                return;
            }
            
            Long orderId = Long.parseLong(orderIdStr);
            Order order = orderService.getOrderById(orderId);
            
            if (order == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "订单不存在");
                out.print(objectMapper.writeValueAsString(result));
                return;
            }
            
            // 验证订单是否属于当前商户
            if (!order.getMerchantId().equals(merchant.getUserId())) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "无权操作该订单");
                out.print(objectMapper.writeValueAsString(result));
                return;
            }
            
            // 验证订单状态（必须是售后中状态）
            if (order.getStatus() != 5) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "订单状态不正确，只能处理售后中的订单");
                out.print(objectMapper.writeValueAsString(result));
                return;
            }
            
            // 将订单状态改为已完成（3）
            order.setStatus(3);
            boolean success = orderService.updateOrder(order);
            
            Map<String, Object> result = new HashMap<>();
            if (success) {
                result.put("success", true);
                result.put("message", "售后订单已完成");
            } else {
                result.put("success", false);
                result.put("message", "操作失败，请重试");
            }
            out.print(objectMapper.writeValueAsString(result));
        } catch (NumberFormatException e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "订单ID格式错误");
            out.print(objectMapper.writeValueAsString(result));
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "服务器错误：" + e.getMessage());
            out.print(objectMapper.writeValueAsString(result));
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 批量删除订单
     */
    private void batchDeleteOrders(HttpServletRequest request, HttpServletResponse response, User merchant)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String[] orderIdStrs = request.getParameterValues("orderIds[]");
            
            if (orderIdStrs == null || orderIdStrs.length == 0) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "请选择要删除的订单");
                out.print(objectMapper.writeValueAsString(result));
                return;
            }
            
            List<Long> orderIds = new java.util.ArrayList<>();
            for (String orderIdStr : orderIdStrs) {
                try {
                    Long orderId = Long.parseLong(orderIdStr.trim());
                    orderIds.add(orderId);
                } catch (NumberFormatException e) {
                    // 忽略无效的ID
                }
            }
            
            if (orderIds.isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "没有有效的订单ID");
                out.print(objectMapper.writeValueAsString(result));
                return;
            }
            
            int successCount = 0;
            int failCount = 0;
            
            for (Long orderId : orderIds) {
                try {
                    // 验证订单是否属于当前商户
                    Order order = orderService.getOrderById(orderId);
                    if (order == null || !order.getMerchantId().equals(merchant.getUserId())) {
                        failCount++;
                        continue;
                    }
                    
                    // 逻辑删除订单（将状态设为已取消）
                    order.setStatus(4); // 已取消
                    boolean success = orderService.updateOrder(order);
                    if (success) {
                        successCount++;
                    } else {
                        failCount++;
                    }
                } catch (Exception e) {
                    failCount++;
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            if (failCount == 0) {
                result.put("success", true);
                result.put("message", "成功删除 " + successCount + " 个订单");
            } else {
                result.put("success", true);
                result.put("message", "成功删除 " + successCount + " 个订单，失败 " + failCount + " 个");
            }
            out.print(objectMapper.writeValueAsString(result));
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "服务器错误：" + e.getMessage());
            out.print(objectMapper.writeValueAsString(result));
        } finally {
            out.flush();
            out.close();
        }
    }
}

